import 'dart:collection';

import 'package:flutter/material.dart';


class EntryMessage {
  final String id;
  final String content;

  EntryMessage({required this.id, required this.content});
}

class RoomEntryMessage extends StatefulWidget {
  const RoomEntryMessage({Key? key}) : super(key: key);

  @override
  _RoomEntryMessageState createState() => _RoomEntryMessageState();
}

class _RoomEntryMessageState extends State<RoomEntryMessage> {
  final Queue<EntryMessage> _messageQueue = Queue<EntryMessage>();
  final List<EntryMessage> _activeMessages = [];
  final int _maxVisible = 3;

  void addEntryMessage(String content) {
    final msg = EntryMessage(id: UniqueKey().toString(), content: content);
    _messageQueue.add(msg);
    _tryShowNext();
  }

  void _tryShowNext() {
    if (_activeMessages.length >= _maxVisible) return;
    if (_messageQueue.isEmpty) return;

    final next = _messageQueue.removeFirst();
    setState(() {
      _activeMessages.add(next);
    });
  }

  void _removeMessage(String id) {
    setState(() {
      _activeMessages.removeWhere((msg) => msg.id == id);
    });
    _tryShowNext();
  }

  @override
  void dispose() {
    _messageQueue.clear();
    _activeMessages.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      right: 16,
      bottom: 120, // 不与礼物消息重叠
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: _activeMessages.map((msg) {
          return EntryMessageItem(
            key: ValueKey(msg.id),
            message: msg,
            onDismissed: () => _removeMessage(msg.id),
          );
        }).toList(),
      ),
    );
  }
}

class EntryMessageItem extends StatefulWidget {
  final EntryMessage message;
  final VoidCallback onDismissed;

  const EntryMessageItem({
    Key? key,
    required this.message,
    required this.onDismissed,
  }) : super(key: key);

  @override
  State<EntryMessageItem> createState() => _EntryMessageItemState();
}

class _EntryMessageItemState extends State<EntryMessageItem> with TickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<Offset> _animationIn;
  late final Animation<Offset> _animationOut;

  bool _exiting = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);

    _startInAnimation();
  }

  Future<void> _startInAnimation() async {
    final inController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animationIn = Tween<Offset>(
      begin: const Offset(1.0, 0.0), // 从右侧进入
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: inController, curve: Curves.easeOut));

    _controller.dispose();
    _controller = inController;

    await _controller.forward();
    await Future.delayed(const Duration(seconds: 2));
    _startOutAnimation();
  }

  Future<void> _startOutAnimation() async {
    setState(() => _exiting = true);

    final outController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animationOut = Tween<Offset>(
      begin: Offset.zero,
      end: const Offset(-1.0, 0.0), // 向左退出
    ).animate(CurvedAnimation(parent: outController, curve: Curves.easeIn));

    _controller.dispose();
    _controller = outController;

    await _controller.forward();
    widget.onDismissed();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SlideTransition(
      position: _exiting ? _animationOut : _animationIn,
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.orange,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Text(
          widget.message.content,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}



